#!/usr/bin/env python
# -*- coding:utf-8 -*-

import sys
# reload(sys)
# sys.setdefaultencoding( "utf-8" )
from pymysqlreplication import BinLogStreamReader
from pymysqlreplication.event import GtidEvent,XidEvent,QueryEvent
from pymysqlreplication.row_event import (
    DeleteRowsEvent,
    UpdateRowsEvent,
    WriteRowsEvent,
)

mysql_settings = {'host': 'rm-bp18d2k8f68om091mo.mysql.rds.aliyuncs.com',
                  'port': 3306, 'user': 'root', 'passwd': '*#Forke110'}

stream = BinLogStreamReader(
    connection_settings=mysql_settings,
    # resume_stream=True,
    server_id=14,
    only_schemas='dyj',
    # log_pos=4,
    # log_file='mysql-bin.000089',
    # blocking=True,  
    # ignored_events=[XidEvent,QueryEvent,GtidEvent],
    only_events=[DeleteRowsEvent,
                 WriteRowsEvent, UpdateRowsEvent]
)
i=0
for binlogevent in stream:
    # binlogevent.dump()
    # if i>100:
        # break
    prefix = "%s:%s:" % (binlogevent.schema, binlogevent.table)

    for row in binlogevent.rows:
        if isinstance(binlogevent, DeleteRowsEvent):
            vals = row["values"]
            print(vals)
        elif isinstance(binlogevent, UpdateRowsEvent):
            vals = row["after_values"]
            # print(prefix, 'update')
            print(prefix, 'update',vals)
        elif isinstance(binlogevent, WriteRowsEvent):
            vals = row["values"]
            print(prefix,'insert')
            print(prefix,'insert', vals)
        binlogevent.dump()
        sys.stdout.flush()  

stream.close()
